<%@page import="com.bionic.banking.logic.DomainUtil"%>
<%@page import="java.io.*"%>
<%@page import="java.util.Locale"%>
<%@page contentType="text/html"%>
<%@page pageEncoding="UTF-8"%>
<%@page import="java.util.Locale" %>
<%@taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %>
<%@taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%> 
<%@taglib uri="../WEB-INF/taglib.tld" prefix="m" %> 

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
    "http://www.w3.org/TR/html4/loose.dtd">
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title>Create a Customer</title>

        <link rel="stylesheet"  type="text/css" href="../resources/css/demos.css"/>   
        <link rel="stylesheet" type="text/css" href="../resources/themes/smoothness/ui.all.css" />
        <link rel="stylesheet" href="../resources/themes/cupertino/jquery-ui.css" />                    

        <script type="text/javascript" src="../resources/script/jquery.js"></script>
        <script type="text/javascript" src="../resources/script/jquery.min.js"></script>        
        <script type="text/javascript" src="../resources/script/ui/jquery-ui.min.js">
        </script>              
        <script type="text/javascript">                                   
            $(function()
            {                
                //1. Create the tabs
                $("#tabs").tabs();
                        
                //2. Filter non-digits from input value.
                $('input[type="number"]').keyup(function(e)
                {
                    if (/\D/g.test(this.value))
                        this.value = this.value.replace(/\D/g, '');
                });                     
                 
                //3. Load image from file to JSP <img> tag
                $(":file").change(function(){                    
                    var file = this.files.item(0);
                    var url =  window.URL || window.webkitURL || window.mozURL || window.msURL;             
                    var blobURLref = url.createObjectURL(file,{autoRevoke:false});   
                    
                    //set blobURLref to display image
                    var img = $('#portret');
                    //img.onload=function(e) { alert(e.response.previewUrl()); }; 
                    img.attr("src", blobURLref);//var servletPath = "../ImageServlet?photoFile="+path;
                    
                    //get arraybuffer to be stored to dtabase
                    var xhr = new XMLHttpRequest();
                    xhr.open('GET', blobURLref, true);
                    xhr.responseType = 'arraybuffer';                    
                    xhr.onload = function(e) {           
                      //set image buffer (to be saved to DB)
                      var buffString = bufferToString(this.response);
                      $('#imageBuffer').val(buffString); 
                    };
                    xhr.send();                    
                });
                 
                //4. validation before save
                $("[required=true]").after("<span></span>");
                $("#btnSubmit").click(function()
                {       
                    //$.validate();
                    var error=false;
                    $("span").text("");//Clear all error message
                                
                    $("[class~=Red]").removeClass("Red");
                    
                    if(trim($("#firstName").val())==""){
                        $("#firstName").next().text(" Please enter first name");
                        $("#firstName").addClass("Red");
                        error=true;
                    }
                    if(trim($("#lastName").val())==""){
                        $("#lastName").next().text(" Please enter last name");
                        $("#lastName").addClass("Red");
                        error=true;
                    }                    
                    if(trim($("#age").val())==""){
                        $("#age").next().text(" Please enter age");
                        $("#age").addClass("Red");
                        error=true;
                    }
                    if(trim($("#email").val())==""){
                        $("#email").next().text(" Please enter email");
                        $("#email").addClass("Red");
                        error=true;
                    }else if(!isEmail($("#email").val())){
                        $("#email").next().text(" Please enter valid Email");
                        $("#email").addClass("Red");
                        error=true;
                    }
                                
                    if(trim($("#password").val())==""){
                        $("#password").next().text(" Please enter password");
                        $("#password").addClass("Red");
                        error=true;
                    }
                    else if($("#password").val()!=$("#c_password").val()){
                        $("#c_password").addClass("Red");
                        $("#c_password").parent().append("<span> Please verify password</span>");                                         
                        error=true;
                    }
                     
                    if($("[name=rbGender]:checked").size()==0){                                      
                        $("#gender").addClass("Red");
                        $("#gender").parent().append("<span> Please select Gender</span>");
                        error=true;
                    }
                    
                    var genderName = $("[name=rbGender]:checked").val();
                    $("#gender").val(genderName == 'f' ? <%= Boolean.TRUE%> : <%= Boolean.FALSE%>);
                    
                    //red error style
                    $("[class=Red]").eq(0).focus();
                    return !error;
                });
            });
                    
            function bufferToString( buf ) {
                var view = new Uint8Array( buf );
                return Array.prototype.join.call(view, ",");
            }
            function stringToBuffer( str ) {
                var arr = str.split(",")
                  , view = new Uint8Array( arr );
                return view.buffer;
            }

            function isNumber(str)
            {
                var regex = /^[0-9]*$/;
                return regex.test(str);
            }
            function isWord(str)
            {
                var regex = /[a-zA-Z]*/;
                return regex.test(str);
            }
            function isFloat(str)
            {
                var regex = /^[0-9]*\\.?[0-9]*$/;
                return regex.test(str);
            }
                
            function trim(x) {
                return x.replace(/^\s+|$\s+/,'');
            }
            function isValidJawwal(m) {
                var exp = /059-?[7-9]\d{6}/;
                return exp.test(m);
            }
            function isEmail(str)
            {
                var regex = /\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*/;
                return regex.test(str);
            }
            function isURL(str)
            {
                var regex = /^http:\/\/([\w-]+\.)+[\w-]+(\/[\w- .\/?%&=]*)?$/;
                return regex.test(str);
            }          
        </script>
        <style type="text/css">   
            body 
            {
                font-size: 62.5%;
                background:lightgrey;
            } 
            .Red{
                border: solid 2px red;
            }
            span{
                color:red;
            }
            .floatLeft{
                float:left;
                margin-right:5px;
            }
        </style>                      
    </head>
    <body>
        <h3>New customer</h3>
        <jsp:useBean id="domainHelperBean" class="com.bionic.banking.logic.DomainUtil" scope="page"/>
        <form id="newCustomerForm" action="../Controller" method="post">
            <input type="hidden" id="command" name="command" value ="createCustomer"/>  
            <div id="tabs">
                <ul>
                    <li><a href="#divCustomer">Personal info</a></li>
                    <li><a href="#divAddress">Address</a></li>
                    <!--li><a href="#divAccounts">Bank accounts</a></li-->
                </ul>                  
                <div id="divCustomer" >
                    <table id="tblCustomer">      
                        <tr>
                            <td>Login:</td>
                            <td><input id="login" name="login" value="" required="true"/> </td>
                            <td>Email</td>
                            <td><input type="text" id = "email" name="email" /></td>
                        </tr>    
                        <tr>
                            <td>Password:</td>
                            <td><input id="password" name="password" type="password"/></td>
                            <td>Password (verify):</td>
                            <td><input id="c_password" name="c_password" type="password"/></td>
                        </tr>   
                        <tr><td colspan="4" ><hr/></td></tr>
                        <tr>
                            <td>First Name</td>
                            <td>
                                <input required="true" type="text" id = "firstName" name="firstName" />
                            </td>
                            <td>
                                Photo file
                                <input type="hidden" id = "imageBuffer" name="imageBuffer" />       
                            </td>
                            <td>                                
                               <input type="file" id = "photoFilePath" name="photoFilePath" />              
                            </td>
                       </tr>
                       <tr>
                            <td>Last Name</td>
                            <td>
                                <input required="true" type="text" id = "lastName" name="lastName" />
                            </td>
                            <td rowspan="4">                                
                                <img id="portret" name="portret" width="100" height="100"  />    
                            </td>
                        </tr>
                        <tr>
                            <td>Middle Name</td>
                            <td>
                                <input type="text" id = "middleName" name="middleName" />
                            </td>                            
                        </tr>
                        <tr>
                            <td>Age</td>                  
                            <td width="50">
                                <input type="text" id = "age" name="age" required="true" 
                                       <m:maskedInput mask="[0-9]{2}"/> >
                            </td>
                        </tr>
                        <tr><td>Gender</td><td>        
                                <input id="gender" name="gender" type="hidden" value=""/>
                                <div class="floatLeft">                                    
                                    <input id="rbMale" name="rbGender" type="radio" value="m" />
                                    <label for=rbMale>Male</label>
                                    <input id="rbFemale" name="rbGender" type="radio" value="f" />
                                    <label for=rbFemale>Female</label>
                                </div>
                            </td></tr>
                        <tr>
                            <td>Phone</td>
                            <td><input type="text" id = "phone" name="phone" /></td>
                            <td>Fax</td>
                            <td><input type="text" id = "fax" name="fax" /></td>
                        </tr>                        
                    </table>
                </div>
                <div id="divAddress">                      
                    <table id="tblAddress">              
                        <tr><td>Country</td>
                            <td>                       
                              <select name="country" id="country" />  
                                <c:forEach var="country" items="${domainHelperBean.getCountries()}" >
                                    <option value="${country.getCode()}"> ${country} </option>
                                </c:forEach>
                               </select>
                            </td>
                        </tr>        
                        <tr>
                            <td>Postal Code</td>
                            <td><input type="text" id = "postalcode" name="postalcode" /></td>
                        </tr>        
                        <tr>
                            <td>Region</td>
                            <td><input type="text" id = "region" name="region" /> </td>
                        </tr>
                        <tr>
                            <td>City</td>
                            <td><input type="text" id = "city" name="city" /> </td>
                        </tr>
                        <tr>
                            <td>Street</td>
                            <td>
                                <input type="text" id = "street" name="street" />
                            </td>
                        </tr>
                        <tr>
                            <td>Line1</td>
                            <td>
                                <input type="text" id = "line1" name="line1"  />
                            </td>
                        </tr>
                        <tr>
                            <td>Line2</td>
                            <td>
                                <input type="text" id = "line2" name="line2"  />
                            </td>
                        </tr>
                        <tr/>
                        <tr/>
                        <tr/>
                        <tr/>
                    </table>
                </div>        
            </div>
            <input type="submit" id="btnSubmit" value="Save" />     
            <a href="Controller?command=viewCustomersList"><strong>Go to List</strong></a> 
        </form>
    </body>
</html>